package utils

import (
	"path/filepath"
	"strings"
)

func SanitizePath(path string) string {
	// 清理路径
	cleanedPath := filepath.Clean(path)

	// 获取目录和文件名
	dir, file := filepath.Split(cleanedPath)

	// 处理文件名中的非法字符
	sanitizedFile := SanitizeFileName(file)

	// 重新组合路径
	sanitizedPath := filepath.Join(dir, sanitizedFile)

	// 检查路径长度
	if !CheckPathLength(sanitizedPath) {
		// 处理路径过长的情况
		sanitizedPath = sanitizedPath[:260]
	}

	return sanitizedPath
}

func IsReservedName(name string) bool {
	reservedNames := []string{
		"CON", "PRN", "AUX", "NUL",
		"COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
		"LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
	}

	for _, reserved := range reservedNames {
		if strings.ToUpper(name) == reserved {
			return true
		}
	}

	return false
}

func SanitizeFileName(name string) string {
	if IsReservedName(name) {
		return "_" + name
	}

	illegalChars := `<>:"/\|?*`
	for _, char := range illegalChars {
		name = strings.ReplaceAll(name, string(char), "_")
	}

	return name
}

func CheckPathLength(path string) bool {
	maxLength := 260
	return len(path) <= maxLength
}
